<template>
  <div class="login">
    <el-form
      ref="loginForm"
      label-position="top"
      :model="formData"
      label-width="80px"
      :rules="myRules"
    >
      <h2>登录</h2>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formData.password"></el-input>
      </el-form-item>
      <el-form-item>
        <!-- 点击登录之后，isloading变成true,在点第二次就会判断，如果isLoading是true，则不执行 -->
        <el-button type="primary" @click="onSubmit" :loading="isLoading"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
// import request from "@/utils/ruquest";//封装到api/user.js
import { login } from "@/api/user";
export default {
  name: "LoginIndex",
  data() {
    return {
      formData: {
        phone: "18201288771",
        password: "111111",
      },
      //表单验证
      myRules: {
        phone: [
          //光标离开触发
          { required: true, message: "手机号为必填项", trigger: "blur" },
          { pattern: /^1\d{10}$/, message: "手机号不合法", trigger: "blur" }, //1开头,10个数字
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 3, max: 6, message: "密码长度应该在3~6位", trigger: "blur" },
        ],
      },
      isLoading: false, //是否在请求中
    };
  },
  methods: {
    //登录的时候再验证一次
    onSubmit() {
      this.isLoading = true;
      // console.log("submit!");loginForm绑定了ref，可以获取表单,validate可以重新验证
      this.$refs.loginForm
        .validate()
        .then(() => login(this.formData))
        //验证通过,可以发送登录信息给接口（弹窗）use.ElementUI会给this一个message方法
        // this.$message.success("验证通过,可以发送登录信息给接口");
        // .then((res) => {
        //   console.log(res);
        // });
        .then((res) => {
          // console.log(res);
          // console.log(res.data.content); //登录的token
          const { data } = res;
          if (data.success) {
            this.$message.success("登录成功");
            //登录成功跳转到首页
            this.$store.commit("saveTokenInfo", data.content);
            // this.$router.push({ name: "home" });
            this.$router.push(this.$route.query.redirect || "/");
          } else {
            this.$message.error("登录失败");
          }
        })
        .catch(() => {
          //表单验证失败
          this.$message.error("表单验证失败");
        })
        .finally(() => {
          //最后
          this.isLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
//整体样式
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
//登录样式
.el-form {
  width: 300px;
  background: #fff;
  padding: 30px;
  border-radius: 10px;
  .el-button {
    width: 100%;
  }
}
</style>
